import cv2
import numpy as np
 
# 读取图像
# image = cv2.imread('./data/images/6_1.png')
image = cv2.imread('./data/images/3_1.png')
 
# 转换为灰度图
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 降噪
blur = cv2.GaussianBlur(gray_image, (7,7), 0)
# 动态阈值二值化
_, binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)  # 自适应阈值‌:ml-citation{ref="3,4" data="citationList"}
    
# 形态学闭合操作
kernel = np.ones((3,3), np.uint8)
closed = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)  # 连接断裂边缘‌:ml-citation{ref="5,7" data="citationList"}

# 应用Canny边缘检测
edges = cv2.Canny(closed, 100, 200)

# 查找所有外轮廓
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  # ‌:ml-citation{ref="1,6" data="citationList"}

# 按面积筛选最大轮廓
max_contour = max(contours, key=cv2.contourArea)
if len(contours) == 0:
    raise ValueError("未检测到有效轮廓")

# 在原始图像上绘制轮廓（需先完成之前的轮廓检测步骤）
cv2.drawContours(
    edges,         # 原始图像
    [max_contour], # 输入轮廓（推荐使用原始轮廓而非近似后的坐标）
    -1,            # 绘制所有轮廓
    (255, 0, 0),   # BGR颜色值（蓝色）
    10              # 线条粗细
)
# 显示结果
cv2.imshow('Edges', edges)
print(max_contour)
# 按q键退出
if cv2.waitKey(0) & 0xFF == ord('q'):
    cv2.destroyAllWindows()
